<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Logic\Detail;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Client\Contract\ClientContract;
use MoChat\App\Client\Contract\ClientTagPivotContract;
use MoChat\App\Client\Contract\ClientTagContract;

/**
 * 客户详情顶部信息.
 *
 * Class IndexLogic
 */
class HeadLogic
{
    /**
     * @Inject
     * @var ClientContract
     */
    protected $clientService;

    /**
     * @Inject
     * @var ClientTagPivotContract
     */
    protected $clientTagPivotService;

    /**
     * @Inject
     * @var ClientTagContract
     */
    protected $clientTagService;

    /**
     * 成员详情顶部信息.
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle(array $params): array
    {
        $data = [];
        //根据标签查询用户ID
        $data = $this->clientService->getClientById((int)$params['clientId'], ['id', 'b2b_client_name', 'enterprise_name', 'last_order_at', 'follow_person_id']);
        //查询客户的企业微信ID
        $contactId = Db::table('client_contact_pivot')->where('client_id', $data['id'])->value('contact_id');
        // 查询客户标签
        $data['tag'] = $this->getClientTag($data['id']);
        //查询跟进次数
        $data['followCount'] = Db::table('client_follow_record')->where('client_id', $data['id'])->count('id');
        //跟进人
        $data['followPersonName'] = Db::table('work_employee')->where('id', $data['followPersonId'])->value('name');
        $data['lastMessageTime'] = Db::table('work_contact_employee')->where('employee_id', $data['followPersonId'])->where('contact_id', $contactId)->value('last_message_time');

        return $data;
    }

    /**
     * 获取B2B客户标签.
     * @param $clientId
     * @return array
     */
    private function getClientTag($clientId)
    {
        $clientTag = $this->clientTagPivotService->getClientTagPivotsByOtherId($clientId);
        if (empty($clientTag)) {
            return [];
        }
        $tagIds = array_unique(array_column($clientTag, 'clientTagId'));
        // 根据标签id查询标签名称
        $tagInfo = $this->clientTagService->getClientTagsById($tagIds, ['id', 'name']);
        if (empty($tagInfo)) {
            return [];
        }
        $tagInfo = array_column($tagInfo, null, 'id');
        $tagName = [];
        foreach ($clientTag as &$raw) {
            if (isset($tagInfo[$raw['clientTagId']])) {
                $tagName[] = ['name' => $tagInfo[$raw['clientTagId']]['name'], 'id' => $tagInfo[$raw['clientTagId']]['id']];
            }
        }
        unset($raw);
        return $tagName;
    }
}
